package com.ruben.activity.common;

import android.annotation.SuppressLint;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;

import com.example.imagepreview.R;
import com.ruben.adapter.common.PictureAdapter;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class PicturePreviewActivity extends AppCompatActivity {
    public static final String IMAGES_DATA_LIST = "DATA_LIST";
    public static final String IMAGE_NUM = "IMAGE_NUM";
    /**
     * 当前页码
     */
    private TextView numberTv;
    private ViewPager viewPager;

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_picture_preview);
        initView();
    }

    /**
     * 初始化视图
     */
    @SuppressLint("SetTextI18n")
    @SuppressWarnings("unchecked")
    @RequiresApi(api = Build.VERSION_CODES.N)
    private void initView() {
        viewPager = findViewById(R.id.pager);
        numberTv = findViewById(R.id.number);
        TextView allTv = findViewById(R.id.all);
        // 获取数据
        List<String> imageList = Optional.ofNullable((List<String>) getIntent().getSerializableExtra(IMAGES_DATA_LIST)).orElse(new ArrayList<>());
        // 获取当前页码，如果没获取到，则为-1
        int position = getIntent().getIntExtra(IMAGE_NUM, -1);
        int dataLength = imageList.size();
        // 设置适配器，并给定点击事件，触发后执行finish()
        viewPager.setAdapter(new PictureAdapter(imageList, this, PicturePreviewActivity.this::finish));
        // 设置当前页码（分页）
        viewPager.setCurrentItem(position);
        // 设置当前页码（显示）
        numberTv.setText(position + 1 + "");
        // 设置总页数（显示）
        allTv.setText("/" + dataLength);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                // 页码设置为获取到的当前页码坐标+1
                numberTv.setText(viewPager.getCurrentItem() + 1 + "");
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }
}